package org.starapp.rbac.service;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.starapp.core.persistence.DynamicSpecifications;
import org.starapp.core.persistence.SearchFilter;
import org.starapp.rbac.dao.DepartmentsDao;
import org.starapp.rbac.entity.Departments;

/**
 * @author wangqiang@cisoft.com.cn
 *
 */
//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class DepartmentsService {

	private DepartmentsDao departmentsDao;
	
	@Autowired
	public void setDepartmentsDao(DepartmentsDao departmentsDao) {
		this.departmentsDao = departmentsDao;
	}

	public Departments getDepartments(String departmentId) {
		return departmentsDao.findOne(departmentId);
	}
	
	@Transactional(readOnly = false)
	public void deleteDepartments(String departmentId) {
		departmentsDao.delete(departmentsDao.findOne(departmentId));
	}

	@Transactional(readOnly = false)
	public void saveDepartments(Departments entity) {
		departmentsDao.save(entity);
	}

	public List<Departments> getAllDepartments() {
		return (List<Departments>) departmentsDao.findAll();
	}

	public Page<Departments> getDepartmentsList(Map<String, Object> searchParams, int pageNumber, int pageSize,
			String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Specification<Departments> spec = buildSpecification(searchParams);

		return departmentsDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
	//	if ("auto".equals(sortType)) {
	//		sort = new Sort(Direction.DESC, "");
	//	} else if ("title".equals(sortType)) {
	//		sort = new Sort(Direction.ASC, "");
	//	}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Departments> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<Departments> spec = DynamicSpecifications.bySearchFilter(filters.values(), Departments.class);
		return spec;
	}

}


